package com.weifangfirecontrolformal.weifangfirecontrolformal.web.service.internetofthings.firefightingiot;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.weifangfirecontrolformal.weifangfirecontrolformal.common.base.BaseService;
import com.weifangfirecontrolformal.weifangfirecontrolformal.common.utils.appkit.ConfigKit;
import com.weifangfirecontrolformal.weifangfirecontrolformal.common.utils.appkit.internetofthings.FireFightingIOTJavaKit;
import com.weifangfirecontrolformal.weifangfirecontrolformal.support.model.RespEntity;
import com.weifangfirecontrolformal.weifangfirecontrolformal.support.utils.file.FileStrUtil;
import com.weifangfirecontrolformal.weifangfirecontrolformal.support.utils.requestutil.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class UploadFileService extends BaseService {

	private static final Logger logger = LoggerFactory.getLogger(UploadFileService.class);

	HttpResponse httpResponse;

	/**
	 * 设备导入模板下载
	 * @param httpServletRequest
	 * @return
	 * @throws Exception
	 */
	public ResponseEntity<byte[]> getTemplte(HttpServletRequest httpServletRequest) throws Exception {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("getTemplte","ImportAndExport");
		String domain = ip + methodPath;
		String filepath = "设备导入模板.xlsx";
		byte[] btImg = FileStrUtil.getImageFromNetByUrl(domain);
		HttpHeaders headers = new HttpHeaders();
		// 下载显示的文件名，解决中文名称乱码问题
		String downloadFielName = new String(filepath.getBytes("UTF-8"), "iso-8859-1");
		// 通知浏览器以attachment（下载方式）打开图片
		headers.setContentDispositionFormData("attachment", downloadFielName);
		// application/octet-stream ： 二进制流数据（最常见的文件下载）。
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(btImg, headers, HttpStatus.CREATED);
	}

	/**
	 * 设备导入
	 * @param
	 * @return
	 * @throws Exception
	 */
	public RespEntity deviceImport(MultipartFile file) throws IOException {
		//处理支持form-data和json两种方式
		JSONObject jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("deviceImport","ImportAndExport");
		String domain = ip + methodPath;
		if (!jsonParam.containsKey("isChildren")){
			jsonParam.put("isChildren",2);
			jsonParam.put("transDeviceCode","NO");
		}
		String xml = "";
		httpResponse = HttpRequest.post(domain)
				.form("file",file.getBytes(),"file")
				.form("businessId",jsonParam.getStr("businessId"))
				.form("deviceClassify",jsonParam.getStr("deviceClassify"))
				.form("deviceType",jsonParam.getStr("deviceType"))
				.form("productId",jsonParam.getStr("productId"))
				.form("isChildren",jsonParam.getInt("isChildren"))
				.form("transDeviceCode",jsonParam.getStr("transDeviceCode"))
				.execute();
		xml = httpResponse.body();
		com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
		if(jsonObject.getInteger("code")==1){
			return RespEntity.fail(jsonObject.getString("msg"));
		}
		return RespEntity.success(jsonObject.getString("data"));
	}

	/**
	 * 维保设备导入
	 * @param
	 * @return
	 * @throws Exception
	 */
	public RespEntity maintenanceDeviceImport(MultipartFile file, String businessId, String partitionId, HttpServletRequest httpServletRequest) throws IOException {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("maintenanceDeviceImport","ImportAndExport");
		String domain = ip + methodPath;
		String xml = "";
		httpResponse = HttpRequest.post(domain)
				.form("file",file.getBytes(),"file")
				.form("businessId",businessId)
				.form("partitionId",partitionId)
				.execute();
		xml = httpResponse.body();
		com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
		if(jsonObject.getInteger("code")==1){
			return RespEntity.fail(jsonObject.getString("msg"));
		}
		return RespEntity.success(jsonObject.getString("data"));
	}
	/**
	 * 设备导入模板下载
	 * @param httpServletRequest
	 * @return
	 * @throws Exception
	 */
	public ResponseEntity<byte[]> getBusinessTemplate(HttpServletRequest httpServletRequest) throws Exception {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("getBusinessTemplate","ImportAndExport");
		String domain = ip + methodPath;
		String filepath = "单位导入模板.xlsx";
		byte[] btImg = FileStrUtil.getImageFromNetByUrl(domain);
		HttpHeaders headers = new HttpHeaders();
		// 下载显示的文件名，解决中文名称乱码问题
		String downloadFielName = new String(filepath.getBytes("UTF-8"), "iso-8859-1");
		// 通知浏览器以attachment（下载方式）打开图片
		headers.setContentDispositionFormData("attachment", downloadFielName);
		// application/octet-stream ： 二进制流数据（最常见的文件下载）。
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(btImg, headers, HttpStatus.CREATED);
	}
	/**
	 * 单位导入
	 * @param
	 * @return
	 * @throws Exception
	 */
	public RespEntity businessImport(MultipartFile file, String area, String areaName, HttpServletRequest httpServletRequest) throws IOException {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("businessImport","ImportAndExport");
		String domain = ip + methodPath;
		String xml = "";
		httpResponse = HttpRequest.post(domain)
				.form("file",file.getBytes(),"file")
				.form("area",area)
				.form("areaName",areaName)
				.execute();
		xml = httpResponse.body();
		com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
		if(jsonObject.getInteger("code")==1){
			return RespEntity.fail(jsonObject.getString("msg"));
		}
		return RespEntity.success(jsonObject.getString("data"));
	}
	/**
	 * LED屏和IP音柱上传调用
	 * @param
	 * @return
	 * @throws Exception
	 */
	public RespEntity ipAudioOrLedVideoUpload(MultipartFile file, String deviceClassify, String homeId,HttpServletRequest httpServletRequest) throws IOException {
		String ip = "";
		String methodPath = "";
		if ("8".equals(deviceClassify)){
			ip = ConfigKit.getStr("fireFightingiotJava","config");
			methodPath = FireFightingIOTJavaKit.getStr("uploadLedVideoFile","ImportAndExport");
		}else {
			ip = ConfigKit.getStr("uploadIpAudioFile","config");
			methodPath = FireFightingIOTJavaKit.getStr("uploadIpAudioFile","ImportAndExport");
		}
		String domain = ip + methodPath;
		String xml = "";
		httpResponse = HttpRequest.post(domain)
				.form("file",file.getBytes(),file.getOriginalFilename())
				.form("deviceClassify",deviceClassify)
				.form("homeId",homeId)
				.form("number","number")
				.execute();
		xml = httpResponse.body();
		cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(xml);;
		if(jsonObject.getInt("code")==1){
			return RespEntity.fail(jsonObject.getStr("msg"));
		}
		return RespEntity.success(jsonObject.getJSONObject("data"));
	}
	/**
	 * 卸油证据链上传
	 * @param
	 * @return
	 * @throws Exception
	 */
	public RespEntity uploadChainOfEvidenceFile(MultipartFile file) throws IOException {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");;
		String methodPath = FireFightingIOTJavaKit.getStr("uploadChainOfEvidenceFile","ImportAndExport");;
		String domain = ip + methodPath;
		String xml = "";
		httpResponse = HttpRequest.post(domain)
				.form("file",file.getBytes(),file.getOriginalFilename())
				.execute();
		xml = httpResponse.body();
		cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(xml);;
		if(jsonObject.getInt("code")==1){
			return RespEntity.fail(jsonObject.getStr("msg"));
		}
		return RespEntity.success(jsonObject.getJSONObject("data"));
	}
	/**
	 * 错误列表导出
	 * @param
	 * @return
	 */
	public ResponseEntity<byte[]> downloadExcel(String fileName, HttpServletRequest httpServletRequest) throws Exception {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("downloadExcel","ImportAndExport");
		String domain = ip + methodPath;
		byte[] btImg = FileStrUtil.getImageFromNetByUrl(domain+"?fileName="+HttpUtil.encodeUtf8(fileName));
		HttpHeaders headers = new HttpHeaders();
		// 下载显示的文件名，解决中文名称乱码问题
		String downloadFielName = new String(fileName.substring(fileName.lastIndexOf("/"),fileName.length()).getBytes("UTF-8"), "iso-8859-1");
		// 通知浏览器以attachment（下载方式）打开图片
		headers.setContentDispositionFormData("attachment", downloadFielName);
		// application/octet-stream ： 二进制流数据（最常见的文件下载）。
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(btImg, headers, HttpStatus.CREATED);
	}

	/**
	 * 设备导出
	 * @param httpServletRequest
	 * @return
	 * @throws Exception
	 */
	public ResponseEntity<byte[]> getDeviceTemplte(Map<String,Object> map, HttpServletRequest httpServletRequest) throws Exception {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("getDeviceTemplte","ImportAndExport");
		String domain = ip + methodPath;
		Set<String> set = map.keySet();
		if (set.size()>0){
			domain=domain+"?";
			for (String str : set){
				if(map.get(str)!=null && StrUtil.isNotBlank(map.get(str).toString())){
					domain=domain+str+"="+ HttpUtil.encodeUtf8(map.get(str).toString())+"&";
				}else{
					domain=domain+str+"="+map.get(str)+"&";
				}
			}
			domain=domain.substring(0,domain.length()-1);
		}
		String filepath = "设备导出.xlsx";
		byte[] btImg = FileStrUtil.getImageFromNetByUrl(domain);
		HttpHeaders headers = new HttpHeaders();
		// 下载显示的文件名，解决中文名称乱码问题
		String downloadFielName = new String(filepath.getBytes("UTF-8"), "iso-8859-1");
		// 通知浏览器以attachment（下载方式）打开图片
		headers.setContentDispositionFormData("attachment", downloadFielName);
		// application/octet-stream ： 二进制流数据（最常见的文件下载）。
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(btImg, headers, HttpStatus.CREATED);
	}

	/**
	 * 报警记录导出
	 * @param httpServletRequest
	 * @return
	 * @throws Exception
	 */
	public ResponseEntity<byte[]> exportDeviceAlarmLog(Map<String,Object> map, HttpServletRequest httpServletRequest) throws Exception {
		String ip = ConfigKit.getStr("fireFightingiotJava","config");
		String methodPath = FireFightingIOTJavaKit.getStr("exportDeviceAlarmLog","ImportAndExport");
		String domain = ip + methodPath;
		Set<String> set = map.keySet();
		if (set.size()>0){
			domain=domain+"?";
			for (String str : set){
				if(map.get(str)!=null && StrUtil.isNotBlank(map.get(str).toString())){
					domain=domain+str+"="+ HttpUtil.encodeUtf8(map.get(str).toString())+"&";
				}else{
					domain=domain+str+"="+map.get(str)+"&";
				}
			}
			domain=domain.substring(0,domain.length()-1);
		}
		String filepath = "报警记录导出.xlsx";
		byte[] btImg = FileStrUtil.getImageFromNetByUrl(domain);
		HttpHeaders headers = new HttpHeaders();
		// 下载显示的文件名，解决中文名称乱码问题
		String downloadFielName = new String(filepath.getBytes("UTF-8"), "iso-8859-1");
		// 通知浏览器以attachment（下载方式）打开图片
		headers.setContentDispositionFormData("attachment", downloadFielName);
		// application/octet-stream ： 二进制流数据（最常见的文件下载）。
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(btImg, headers, HttpStatus.CREATED);
	}

	/**
	 * @Author YangYu
	 * @Description 显示控制装置历史数据记录导出
	 * @Date Created in 10:07 2022/8/25
	 * @Param [jsonParam]
	 */

	public RespEntity exportWaterColumnBoxDataLog(JSONObject jsonParam) {
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		return restJava(jsonParam,"fireFightingiotJava","exportWaterColumnBoxDataLog","ImportAndExport");
	}

	/**
	 * @Author YangYu
	 * @Description 设备导出
	 * @Date Created in 10:07 2022/8/25
	 * @Param [jsonParam]
	 */

	public RespEntity getDeviceExport(JSONObject jsonParam) {
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		return restJava(jsonParam,"fireFightingiotJava","getDeviceExport","ImportAndExport");
	}
}
